package booking.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import booking.misc.User;
import booking.misc.DBConnectionData;

public class UserWindow extends JFrame implements ActionListener {
    private static final String ADD = "add";
    private static final String UPDATE = "update";
    private static final String REMOVE = "remove";
    private UserModel userModel;
    JTable table;
    private JButton updateBtn;
    private JButton removeBtn;
    // - Konstruktor som skapar GUI't -------------------------------------
    public UserWindow() {
  
    	userModel = new UserModel();

    	Vector<User> users = loadUsers();
    	
    	userModel.setUsers(loadUsers());
        
        table = new JTable(userModel);
        table.setPreferredScrollableViewportSize(new Dimension(400, 100));
        table.getColumnModel().getColumn(0).setPreferredWidth(30);
        table.getColumnModel().getColumn(1).setPreferredWidth(130);
        table.getColumnModel().getColumn(2).setPreferredWidth(130);
        table.getColumnModel().getColumn(3).setPreferredWidth(130);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);
        
        JScrollPane sp = new JScrollPane(table);
        add(sp, BorderLayout.CENTER);
        JPanel bottomPnl = new JPanel(new FlowLayout());
        add(bottomPnl, BorderLayout.PAGE_END);
        
        JButton btn = new JButton("Add");
        btn.addActionListener(this);
        btn.setActionCommand(ADD);
        bottomPnl.add(btn);
        
        updateBtn = new JButton("Update");
        updateBtn.addActionListener(this);
        updateBtn.setActionCommand(UPDATE);
        bottomPnl.add(updateBtn);
        
        removeBtn = new JButton("Delete");
        removeBtn.addActionListener(this);
        removeBtn.setActionCommand(REMOVE);
        bottomPnl.add(removeBtn);
        
        setTitle("Users");
        setLocationRelativeTo(null);
        pack();
    }
    
 // -- Laddar in samtliga anv��ndare och returnerar dem i en vector
    private Vector<User> loadUsers() {
        Vector<User> vec = new Vector<User>();
        try (Connection conn = DBConnectionData.getConnection()) {
            String sql = "SELECT ID, NAME, Password, Email, Admin "
                    + "FROM users ORDER BY NAME ASC";
            Statement statement = conn.createStatement();
            ResultSet result = statement.executeQuery(sql);
            while (result.next()) {
            	User user = new User(result.getInt(1), result.getString(2),
                        result.getString(3), result.getString(4), result.getBoolean(5));
                vec.add(user);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return vec;
    }
    
    public void actionPerformed(ActionEvent event) {
    	User user;
    	UserDialog ad;
        int row;
        String ac = event.getActionCommand();
        switch (ac) {
        case ADD:
        	ad = new UserDialog(this);
            ad.setVisible(true);
            user = ad.getUser();
            if (user == null) // Canel har tryckts
                return;
            if (user.dbInsert())
            	userModel.setUsers(loadUsers());
            break;
        case UPDATE:
        	row = table.getSelectedRow();
            if (row == -1) // Ingen rad vald
                return;
            user = userModel.getUser(row);
            ad = new UserDialog(this, user);
            ad.setVisible(true);
            user = ad.getUser();
            System.out.println(user);
            if (user == null) // Canel har tryckts
                return;
            if (user.dbUpdate())
            	userModel.setUsers(loadUsers());
            break;
        case REMOVE:
            row = table.getSelectedRow();
            if (row == -1) // Ingen rad vald
                return;
        	user = userModel.getUser(row);
            if (user.dbDelete())
            	userModel.setUsers(loadUsers());
            break;
            }
        }
    }
   

/*------------------------------------------------------------------
 * Modell f���������r tabellinneh���������ll
 */
class UserModel extends AbstractTableModel {
	
	
    private Vector<User> data = new Vector<User>();
    
    public void setUsers(Vector<User> users) {
    	data = users;
    	fireTableDataChanged();
    }
    
    public void addUser(User user) {
        data.addElement(user);
        fireTableDataChanged();
    }
    public void removeRow(int row) {
        data.remove(row);
        fireTableDataChanged();
    }
    public User getUser(int row) {
        return data.get(row);
    }
    public int getColumnCount() {
        return 5;
    }
    public int getRowCount() {
        return data.size();
    }
    public String getColumnName(int col) {
        switch (col) {
        case 0:
            return "Id";
        case 1:
            return "User Name";
        case 2:
            return "User Password";
        case 3:
            return "User Email";
        case 4:
            return "Admin?";
        }
        return "";
    }
    public Object getValueAt(int row, int col) {
    	User user = data.get(row);
        switch (col) {
        case 0:
            return user.getUserId();
        case 1:
            return user.getUserName();
        case 2:
            return user.getUserPassword();
        case 3:
        	return user.getUserEmail();
        case 4:
        	return user.getAdmin();
        }
        return "Unknown";
    }
    public Class<?> getColumnClass(int col) {
        switch (col) {
        case 0:
            return Integer.class;
        case 1:
            return String.class;
        case 2:
            return String.class;
        case 3:
            return String.class;
        case 4:
            return Boolean.class;
        }
        return Object.class;
    }
    public boolean isCellEditable(int row, int col) {
        return false;
    }
}
